const fs = require('fs');
const net = require('net');

const socket = net.createConnection({
    host: 'www.baidu.com', //'duyi.ke.qq.com',
    port: 80
}, () => {
    console.log('连接成功')
});

let receive = null
/**
 * 提炼出响应字符串的消息头和消息体
 * @param {*} response
 */
function parseResponse(response) {
    let index = response.indexOf('<html>')
    const head = response.substring(0, index).trim()
    const body = response.substring(index)
    const headParts = head.split("\r\n")
    const header = headParts.slice(1).map(str => {
        return str.split(": ").map(str => str.trim())
    }).reduce((prev, [key, value]) => {
        prev[key] = value
        return prev
    }, {})
    return { header, body }
}


function isOver() {
    const contentLength = +receive.header['Content-Length']
    const currSize = Buffer.from(receive.body).byteLength
    return currSize > contentLength
}
let body = ''
// 通过监听流的内容获取数据
socket.on('data', chunk => {
    var str = chunk.toString('utf-8')
    if (!receive) {
        receive = parseResponse(str + ' ')
    }
    // body += str
    // console.log('----data---')
    if (!isOver()) {
        receive.body += str
    } else {
        socket.end()
    }
})

// 通过向流写入内容发送数据
// socket.write('1223')

// 发get请求
socket.write(`GET / HTTP/1.1
Host: duyi.ke.qq.com
Connection: keep-alive

`)

// socket.write(`GET / HTTP/1.1
// Host: www.baidu.com
// Connection: keep-alive
// Cookie: BAIDUID=62F5E9E2469F9792EDEAF33E42B045CD:FG=1; BIDUPSID=62F5E9E2469F979299C4FB97279D8584; H_PS_PSSID=34130_34099_34222_31253_33848_33607_34107_34134_26350; PSTM=1625143922; BDSVRTM=8; BD_HOME=1


// `)

socket.on('close', () => {
    console.log('结束了')
    // console.log(receive)
    // fs.promises.writeFile('./temp.txt', body)
})